/**
 * @description Img 该组件是为了统一处理图片路径，主要用于本地的图片
 * @param isTheme 图片是否需要支持换肤（注：不需要支持换肤的直接把src赋值给img标签）
 */
import { useMemo } from 'react';
import { Img as EsyImg, BgImg as EsyBgImg, ImgProps as EsyImgProps, BgImgProps as EsyBgImgPorps } from 'esy-ui';
import { observer } from 'mobx-react-lite';
import { useGlobalStore } from '@/mobx';

export interface ImgProps extends EsyImgProps {
  isTheme?: boolean;
}

// 获取图片地址
const getImgUrl = (src, isTheme, theme) => {
  if (src && !isTheme) return src;
  if (src && theme) {
    const imgUrl = `${theme}${src}`;
    return require(`@/assets/images/${imgUrl}`);
  }
  return '';
};

export const Img = observer((props: ImgProps) => {
  const { src, isTheme, ...rest } = props;
  const { theme } = useGlobalStore();

  // 赋值路径dataUrl
  const dataUrl = useMemo(() => getImgUrl(src, isTheme, theme), [theme, src, isTheme]);

  return <EsyImg src={dataUrl} {...rest} />;
});

/**
 * BgImg
 * @param isTheme 图片是否需要支持换肤（注：不需要支持换肤的直接把src赋值给img标签）
 */
interface BgImgProps extends EsyBgImgPorps {
  isTheme?: boolean;
}

// 对于需要支持换肤的背景图的组件封装
export const BgImg = observer((props: BgImgProps) => {
  const { url, isTheme, ...rest } = props;
  const { theme } = useGlobalStore();

  // 重新赋值路径
  const dataBgUrl = useMemo(() => getImgUrl(url, isTheme, theme), [theme, url, isTheme]);

  return <EsyBgImg url={dataBgUrl} {...rest} />;
});
